﻿/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1
 *
 * The contents of this file are subject to the Mozilla Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 *
 * The Original Code is tyzoh.jp code.
 *
 * The Initial Developer of the Original Code is Kazutaka Kurihara.
 * Portions created by the Initial Developer are Copyright (C) 2007
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * ***** END LICENSE BLOCK ***** */
using System;
using System.Windows.Forms;
using PluginInterface;
using Qurihara;
using System.Collections;
using System.Xml;
using System.IO;
using Qurihara.QBasic;
using System.Text;
using WebIOPlugin.localhost;
using System.Collections.Specialized;
using System.Deployment.Application;
using System.Web;

namespace KotodamaPlugin.WebIOPlugin
{
	/// <summary>
	/// Class1 の概要の説明です。
	/// </summary>
	public class WebIOPlugin :IPlugin
	{

		private MenuItem menuWebIO;
		private MenuItem menuWebIOSave;
        private MenuItem menuWebIOLoad;
        private MenuItem sepa;
        private MenuItem filemenu;

		internal ToolBarDock.ToolBarDockHolder holder = null;

        private WebService ws;
        private string pass = "pass";

		public WebIOPlugin()
		{
            menuWebIO = new MenuItem(Util.IsPropertyTrue("Base.English") ? "Web Folder" : "Webフォルダ");

            menuWebIOSave = new MenuItem(Util.IsPropertyTrue("Base.English") ? "Save" : "保存");
			menuWebIO.MenuItems.Add(menuWebIOSave);
            menuWebIOSave.Click += new EventHandler(menuWebIOSave_Click);

            menuWebIOLoad = new MenuItem(Util.IsPropertyTrue("Base.English") ? "Load" : "読み込み");
            menuWebIO.MenuItems.Add(menuWebIOLoad);
            menuWebIOLoad.Click += new EventHandler(menuWebIOLoad_Click);

            sepa = new MenuItem();
            sepa.Text = "-";

        }

        void menuWebIOLoad_Click(object sender, EventArgs e)
        {
            bool go = true;
            if (Host.Kotodama.Presentation.CurrentSlide.Dirty)
            {
                DialogResult dr = MessageBox.Show("現在開いているファイルはまだ保存していません。続行しますか？", "", MessageBoxButtons.YesNo);
                if (dr == DialogResult.Yes)
                {
                    go = true;
                }
                else if (dr == DialogResult.No)
                {
                    go = false;
                }
            }
            if (go)
            {
                AskId(Util.IsPropertyTrue("Base.English") ? "WebFileID" : "Webフォルダ上のファイルのID");
            }
        }

        void menuWebIOSave_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFile();
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message, "Webフォルダへの保存に失敗しました。保存を中断します。");
            }
        }

        private Qurihara.QBasic.TextEntryForm tef;
        private void AskId(string defaultName)
        {

            tef = new TextEntryForm("Webフォルダからのロード", "ファイル名を入力してください。");
            tef.OutputText = defaultName;
            tef.Closed += new EventHandler(tef_Closed);
            tef.Show();
        }
        private void tef_Closed(object sender, EventArgs e)
        {
            string name = "";
            if (tef != null)
            {
                DialogResult dr = tef.DialogResult;
                if (dr == DialogResult.OK)
                {
                    name = tef.OutputText;
                }
                tef.Dispose();
                tef = null;
            }

            try
            {
                LoadFile(name);
                Host.Kotodama.Control.Invalidate();
            }
            catch (Exception Ex2)
            {
                MessageBox.Show(Ex2.Message, "Webフォルダからの読み込みに失敗しました。読み込みを中断します。");
            }
        }



		#region IPlugin Members
		
		IPluginHost myPluginHost = null;
		string myPluginName = "WebIO Plugin";
		string myPluginAuthor = "K.Qurihara";
		string myPluginDescription = "test plugin";
		string myPluginVersion = "1.0.0";
		
		public void Initialize()
		{
			holder = null;
            //if ( Host.Kotodama.ToolBarManager != null)
            //{
            //}
            //else
            //{// holderが無い ＞ menuについか
            //    //Host.Kotodama.Form.Menu.MenuItems.Add(menuItem);
            //}

            //Menu.MenuItemCollection mic = (Menu.MenuItemCollection)Host.Kotodama.EnvironmentTable["Base.MenuItems"];
            ////mic.Add(menuWebIO);
            //filemenu = Qurihara.QBasic.DrawingUtil.FindByName(mic, Util.IsPropertyTrue("Base.English") ? "File" : "ファイル");
            //if (filemenu != null)
            //{
            //    filemenu.MenuItems.Add(sepa);
            //    filemenu.MenuItems.Add(menuWebIO);
            //}

            try
            {
                ws = GetService();

                //接続チェックしたければコメントアウト
                //ws.HelloWorld();
            }
            catch// (Exception e)
            {
                menuWebIO.Enabled = false;
                //MessageBox.Show(e.Message, "Webフォルダへの接続に失敗しました。Webフォルダは使えません。");
            }
            Util.GetStringProperty("WebIOPlugin.Pass", ref pass);

            //SetImageDLProxy();

            NameValueCollection query = GetQueryStringParameters();
            string file = query["file"];
            if (file != null && file != "") LoadFile(file);
		}

        //private void SetImageDLProxy()
        //{
        //    if (ApplicationDeployment.IsNetworkDeployed)
        //    {
        //        LinkImageElement.ImageDLFactory =
        //            new ImageDLFactoryNet(ws);
        //    }
        //}

        private NameValueCollection GetQueryStringParameters()
        {
            NameValueCollection nameValueTable = new NameValueCollection();

            if (ApplicationDeployment.IsNetworkDeployed)
            {
                string queryString = ApplicationDeployment.CurrentDeployment.ActivationUri.Query;
                nameValueTable = HttpUtility.ParseQueryString(queryString);
            }

            return (nameValueTable);
        }

		void PluginInterface.IPlugin.Dispose()
		{
            //holder = null;
            //if ( Host.Kotodama.ToolBarManager != null)
            //{
            //}
            //else
            //{// holderが無い ＞ menuについか
            //}

			//Menu.MenuItemCollection mic = (Menu.MenuItemCollection)Host.Kotodama.EnvironmentTable["Base.MenuItems"];
			//mic.Remove(menuWebIO);
            //if (filemenu != null)
            //{
            //    filemenu.MenuItems.Remove(sepa);
            //    filemenu.MenuItems.Remove(menuWebIO);
            //}


		}

		public string Description
		{
			get
			{
				// TODO:  Add ctlMain.Description getter implementation
				return myPluginDescription;
			}
		}

		public string Author
		{
			get
			{
				// TODO:  Add ctlMain.Author getter implementation
				return myPluginAuthor;
			}
		}

		public IPluginHost Host
		{
			get
			{
				// TODO:  Add ctlMain.Host getter implementation
				return myPluginHost;
			}
			set
			{
				myPluginHost = value;
			}
		}

		
		public string Name
		{
			get
			{
				// TODO:  Add ctlMain.Name getter implementation
				return myPluginName;
			}
		}
		

		public string Version
		{
			get
			{
				// TODO:  Add ctlMain.Version getter implementation
				return myPluginVersion;
			}
		}

		#endregion

        #region save and load

        public string LoadXmlWeb
        {
            set
            {
                string outs = ws.Load(value, pass);
                if (outs != "")
                {
                    //if(Util.IsPropertyTrue("WebIOPlugin.EnableZip")){
                    //    outs = ZipUtil.UnZipString(outs);
                    //}
                    LoadXml = outs;
                }
                else
                {
                    MessageBox.Show("Webフォルダへの接続ができないか、ファイルが存在しません。読み込みを中断します。");
                }
            }
        }

        public string SaveXmlWeb
        {
            get
            {
                string s = SaveXml;
                //if (Util.IsPropertyTrue("WebIOPlugin.EnableZip"))
                //{
                //    s = ZipUtil.ZipString(s);
                //}
                return ws.Save(s, pass);
            }
        }
        public void LoadFile(string fileID)
        {
            linkBaseDir = "";
            LoadXmlWeb = fileID;
        }
        public string SaveFile()
        {
            linkBaseDir = "";
            string savedId = SaveXmlWeb;
            if (savedId != "")
            {
                Form f = new Form();
                f.Height = 64;
                f.Width = 640;
                f.StartPosition = FormStartPosition.CenterScreen;
                f.FormBorderStyle = FormBorderStyle.FixedToolWindow;
                f.Text = "Webフォルダに保存したファイル名は以下の通りです。メモしてください。";
                TextBox tb = new TextBox();
                tb.Multiline = true;
                f.Controls.Add(tb);
                tb.Dock = DockStyle.Fill;
                tb.ScrollBars = ScrollBars.Vertical;
                tb.Text = savedId;
                f.Show();

                //MessageBox.Show("Webフォルダに保存したファイル名は " + savedId + " です。");
                return savedId;
            }
            else
            {
                MessageBox.Show("Webフォルダへの保存に失敗しました。保存を中断します。");
                return "";
            }
        }

        // LoadXMLやSaveXMLを実行する前に毎回セットすること。
        // これは、LoadXMLとSaveXMLをWeb上で操作するために必要。
        // 通常のセーブとロードはLoadFile()とSaveFile()をつかえ。
        private string linkBaseDir = "";
        public string LinkBaseDir
        {
            get { return linkBaseDir; }
            set { linkBaseDir = value; }
        }

        public string LoadXml
        {
            set
            {
                byte[] b = Encoding.UTF8.GetBytes(value);
                MemoryStream stream = new MemoryStream(b);
                Host.Kotodama.Presentation.CurrentSlide.Load(stream, linkBaseDir);
                stream.Close();
                //presen.CurrentSlideInvalidate();
                linkBaseDir = "";
            }
        }
        public string SaveXml
        {
            get
            {
                MemoryStream stream = new MemoryStream();
                Host.Kotodama.Presentation.CurrentSlide.SaveAsXml(stream, false, linkBaseDir);
                stream.Close();
                byte[] b = stream.GetBuffer();
                //return Encoding.UTF8.GetString(b);
                string outs = Encoding.UTF8.GetString(b);
                char[] nul = { '\0' };
                stream.Close();
                linkBaseDir = "";
                return (outs).TrimEnd(nul);
            }
        }
        #endregion

        #region WebService
        private WebService GetService()
        {
            WebService kw = new WebService();
            string p = "";
            if (ApplicationDeployment.IsNetworkDeployed)
            {
                string site = ApplicationDeployment.CurrentDeployment.ActivationUri.Host;
                kw.Url = kw.Url.Replace("//localhost/"
                    , "//" + site + "/");
            }else
            if (Util.GetStringProperty("WebIOPlugin.ServerUrl", ref p))
            {
                string site = p;
                kw.Url = kw.Url.Replace("//localhost/"
                    , "//" + site + "/");
            }


            return kw;
        }
        #endregion
    }
}
